﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using QLKS.BLL;
using QLKS.Entity;

namespace QLKS.Views
{
    public partial class DMKhachHang_View : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                ViewState["Order"] = string.Empty;
                ViewState["Sort"] = string.Empty;
                ViewState["action"] = string.Empty;

                EnableControl();
                Reload();
                //
                LoadLoaiKhachHang();
            }
        }

        #region Private Method

        void Reload()
        {
            List<DMKhachHang> lstData = DMKhachHangBUS.GetByAll(new DMKhachHang());
            this.gvMain.DataSource = QLKS.Common.Extensions.Sort_List<DMKhachHang>(ViewState["Order"].ToString(), ViewState["Sort"].ToString(), lstData);
            this.gvMain.DataBind();
        }

        void ViewAddUpdatePanel(bool bflag)
        {
            this.pnlMain.Visible = bflag;
            this.pnlUpdate.Visible = !bflag;
        }

        void EnableControl()
        {
            switch (ViewState["action"].ToString())
            {
                case "Add":
                case "Edit":
                    this.btnNew.Enabled = false;
                    this.btnDelete.Enabled = false;
                    this.btnEdit.Enabled = false;
                    this.btnSave.Enabled = true;
                    this.btnCancel.Enabled = true;
                    break;
                default:
                    this.btnNew.Enabled = true;
                    this.btnDelete.Enabled = true;
                    this.btnEdit.Enabled = true;
                    this.btnSave.Enabled = false;
                    this.btnCancel.Enabled = false;
                    break;
            }
        }

        void Clear()
        {
            foreach (Control ctrl in pnlUpdate.Controls)
            {
                if (ctrl is TextBox)
                    ((TextBox)ctrl).Text = string.Empty;
            }
        }

        void ShowAlert(string message)
        {
            string cleanMessage = message.Replace("'", "\'");
            Label lbl = new Label();
            lbl.Text = "<script language='javascript'>" + Environment.NewLine + "window.alert('" + cleanMessage + "')</script>";
            Page.Controls.Add(lbl);
        }

        void LoadLoaiKhachHang()
        {
            try
            {
                ddlLoaiKhachHang.DataTextField = "TenLoaiKhachHang";
                ddlLoaiKhachHang.DataValueField = "MaLoaiKhachHang";
                ddlLoaiKhachHang.DataSource = QLKS.Common.Extensions.Sort_List("ASC", "TenLoaiKhachHang", DMLoaiKhachHangBUS.GetByAll(new DMLoaiKhachHang()));
                ddlLoaiKhachHang.DataBind();
            }
            catch (Exception) { }
            finally
            {
                ddlLoaiKhachHang.Items.Insert(0, new ListItem("Chọn loại khách hàng", "0"));
                ddlLoaiKhachHang.SelectedIndex = 0;
            }
        }

        #endregion

        #region Event On Page

        protected void gvMain_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.gvMain.PageIndex = e.NewPageIndex;
            this.Reload();
        }

        protected void gvMain_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                ((CheckBox)e.Row.FindControl("chkall")).Attributes.Add("onclick", "javascript:SelectAll('" + gvMain.ClientID + "','" + ((CheckBox)e.Row.FindControl("chkall")).ClientID + "')");
            }
        }

        protected void gvMain_Sorting(object sender, GridViewSortEventArgs e)
        {
            if (this.ViewState["Sort"].ToString() != e.SortExpression)
            {
                this.ViewState["Sort"] = e.SortExpression;
                this.ViewState["Order"] = "DESC";
            }
            else
            {
                if (ViewState["Order"].ToString() == "")
                    this.ViewState["Order"] = "DESC";
                else
                {
                    if (ViewState["Order"].ToString() == "DESC")
                    {
                        this.ViewState["Order"] = "ASC";
                    }
                    else
                    {
                        this.ViewState["Order"] = "DESC";
                    }
                }
            }
            Reload();
        }

        protected void btnNew_Click(object sender, EventArgs e)
        {
            ViewState["action"] = "Add";
            EnableControl();
            ViewAddUpdatePanel(false);
            Clear();
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            if (isRefresh) return;
            bool result = false;
            int count = 0;
            try
            {
                CheckBox chk;
                DMKhachHang obj;
                foreach (GridViewRow r in gvMain.Rows)
                {
                    chk = r.FindControl("chkid") as CheckBox;
                    if (chk.Checked)
                    {
                        result = true;
                        Label lbl = r.FindControl("lblID") as Label;
                        obj = new DMKhachHang();
                        obj.MaKhachHang = Convert.ToInt32((lbl == null || lbl.Text == "") ? "0" : lbl.Text.ToString());
                        if (DMKhachHangBUS.Delete(obj))
                            count += 1;
                    }
                }
                if (count == 0) ShowAlert("Chưa dòng thông tin nào được chọn để xóa.");
            }
            catch (Exception)
            {
                ShowAlert("Lỗi khi thao tác dữ liệu.");
                result = false;
            }
            finally
            {
                if (result)
                {
                    ShowAlert("Xóa dữ liệu thành công. Tổng số dòng được xóa:" + count.ToString() + " dòng.");
                    Reload();
                }
            }
        }

        protected void btnEdit_Click(object sender, EventArgs e)
        {
            if (isRefresh) return;
            bool result = false;
            try
            {
                CheckBox chk;
                DMKhachHang obj = new DMKhachHang();
                foreach (GridViewRow r in gvMain.Rows)
                {
                    chk = r.FindControl("chkid") as CheckBox;
                    if (chk.Checked)
                    {
                        result = true;
                        Label lbl = r.FindControl("lblID") as Label;
                        obj.MaKhachHang = Convert.ToInt32((lbl == null || lbl.Text == "") ? "0" : lbl.Text.ToString());
                        ViewState["OldCode"] = obj.MaKhachHang;
                        List<DMKhachHang> lstData = DMKhachHangBUS.GetByAll(obj);
                        if (lstData.Count == 1)
                        {
                            this.txtTenKhachHang.Text = lstData[0].TenKhachHang;
                            this.ddlLoaiKhachHang.SelectedIndex = QLKS.Common.Extensions.GetIndexDropDownList(ddlLoaiKhachHang, lstData[0].LoaiKhachHangID);
                            this.txtCMND.Text = lstData[0].CMND;
                            this.txtDienThoai.Text = lstData[0].DienThoai;
                            this.txtEmail.Text = lstData[0].Email;
                            this.txtDiaChi.Text = lstData[0].DiaChi;
                            this.txtGhiChu.Text = lstData[0].GhiChu;
                        }
                        break;
                    }
                }
                if (!result) ShowAlert("Chưa dòng thông tin nào được chọn.");
            }
            catch (Exception)
            {
                ShowAlert("Lỗi khi thao tác dữ liệu.");
                result = false;
            }
            finally
            {
                if (result)
                {
                    ViewState["action"] = "Edit";
                    EnableControl();
                    ViewAddUpdatePanel(false);
                }
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (isRefresh) return;
            bool result = false;
            try
            {
                DMKhachHang obj = new DMKhachHang();
                obj.TenKhachHang = this.txtTenKhachHang.Text.Trim();
                obj.LoaiKhachHangID = Convert.ToInt32(this.ddlLoaiKhachHang.SelectedValue);
                obj.CMND = this.txtCMND.Text.Trim();
                obj.DienThoai = this.txtDienThoai.Text.Trim();
                obj.Email = this.txtEmail.Text.Trim();
                obj.DiaChi = this.txtDiaChi.Text.Trim();
                obj.GhiChu = this.txtGhiChu.Text.Trim();

                if (ViewState["action"].ToString() == "Add")
                {
                    result = DMKhachHangBUS.Insert(obj);
                }
                else if (ViewState["action"].ToString() == "Edit")
                {
                    obj.MaKhachHang = Convert.ToInt32(ViewState["OldCode"]);
                    result = DMKhachHangBUS.Update(obj);
                }
            }
            catch (Exception)
            {
                ShowAlert("Lỗi khi thao tác dữ liệu.");
                result = false;
            }
            finally
            {
                if (result)
                {
                    ShowAlert("Dữ liệu đã được cập nhật.");
                    this.btnCancel_Click(new object(), new EventArgs());
                }
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            ViewState["action"] = string.Empty;
            EnableControl();
            ViewAddUpdatePanel(true);
            Clear();
            Reload();
        }

        #endregion

        #region Browser Refresh

        private bool refreshState;
        private bool isRefresh;

        protected override void LoadViewState(object savedState)
        {
            object[] AllStates = (object[])savedState;
            base.LoadViewState(AllStates[0]);
            refreshState = bool.Parse(AllStates[1].ToString());
            if (Session["ISREFRESH"] != null && Session["ISREFRESH"] != "")
                isRefresh = (refreshState == (bool)Session["ISREFRESH"]);
        }

        protected override object SaveViewState()
        {
            Session["ISREFRESH"] = refreshState;
            object[] AllStates = new object[3];
            AllStates[0] = base.SaveViewState();
            AllStates[1] = !(refreshState);
            return AllStates;
        }

        #endregion 
    }
}